<?php

namespace app\controller\admin;


use think\Request;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use app\eslib\EsUtils;

class Uploader
{
    public function upload(Request $request)
    {
        $files = $request->file();
        if (!$files) {
            return json(EsUtils::stdmessage(0, '没有文件'));
        }
        $isKeepName = $request->param('keep_name', 0) == 1;
        $iniMaxSize = UploadedFile::getMaxFilesize();
        $data = [];
        try {
            foreach ($files as $file) {
                if ($file->isValid()) {
                    $fileName = $file->getClientOriginalName();
                    if ($isKeepName) {
                        $path = $file->storeAs('uploads', $fileName);
                    } else {
                        $path = $file->store('uploads');
                    }
                    $data[] = [
                        'original_name' => $fileName,
                        'path' => '/' . $path,
                        'size' => EsUtils::formatBytes($file->getSize()),
                        'link' => asset($path),
                        // 'ext' => $file->extension(),
                        // 'mime_type' => $file->getClientMimeType(),
                        'ini_maxsize' => $iniMaxSize,
                    ];
                } else {
                    $data[] = $file->getErrorMessage();
                }
            }
            return json(EsUtils::stdmessage(1, '', $data));
        } catch (\Exception $ex) {
            return json(EsUtils::stdmessage(0, $ex->getMessage(), $ex));
        }
        $fieldName = 'file';
        if ($request->hasFile($fieldName)) {
            return json(EsUtils::stdmessage(0, '没有文件'));
        }
        if ($request->file($fieldName)->isValid()) {
            return json(EsUtils::stdmessage(0, '文件无效'));
        }
        $file = $request->file($fieldName);
        $data = ['file' => $file, 'ext' => $file->extension(), 'path' => $file->path()];
        return json(EsUtils::stdmessage(1, '', $data));
    }
}
